package com.example.multithread;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class Account2 {
    private String name;
    private int asset;
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public Account2(String name, int asset) {
        this.name = name;
        this.asset = asset;
    }

    public void save(int asset) {
        this.readWriteLock.writeLock().lock();
        try {
            this.asset += asset;
            TimeUnit.SECONDS.sleep(1);
            System.out.printf("【%s】修改银行资产，当前的资产为: %10.2f%n", Thread.currentThread().getName(), this.asset / 100.0);
        } catch (Exception e) {

        } finally {
            this.readWriteLock.writeLock().unlock();
        }
    }

    @Override
    public String toString() {
        this.readWriteLock.readLock().lock();
        try {
            TimeUnit.MILLISECONDS.sleep(200);
            return String.format("【%s】账户名称: %s、账户余额: %10.2f %n", Thread.currentThread().getName(), this.name, this.asset / 100.0);
        } catch (Exception e) {
            return null;
        } finally {
            this.readWriteLock.readLock().unlock();
        }
    }
}

/**
 * 读写不均衡，导致很难写入的问题
 */
public class ReentrantReadWriteLockTest2 {
    public static void main(String[] args) {
        Account account = new Account("杨德军", 0);
        int[] money = new int[]{110, 230, 10_000};
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                System.out.println(account);
            }, "取款线程-" + i).start();
        }
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                for (int j = 0; j < money.length; j++) {
                    account.save(money[j]);
                }
            }, "存款线程-" + i).start();
        }
    }
}
